package com.atguigu.ssyx.payment.controller;

import com.atguigu.ssyx.common.result.Result;
import com.atguigu.ssyx.common.result.ResultCodeEnum;
import com.atguigu.ssyx.payment.service.PaymentInfoService;
import com.atguigu.ssyx.payment.service.WeinxinService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * ClassName: WeixinController
 * Package: com.atguigu.ssyx.payment.controller
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-10-17
 * Time: 15:47
 */

@Api(tags = "微信支付接口")
@RestController
@RequestMapping("/api/payment/weixin")
public class WeixinController {

    @Autowired
    private WeinxinService weinxinService;

    @Autowired
    private PaymentInfoService paymentInfoService;


    //调用微信支付系统 生成预付单
    //HTTPClient
    @GetMapping("/createJsapi/{orderNo}")
    public Result createJsapi (@PathVariable("order") String orderNo){

        Map<String,String> map = weinxinService.createJsapi(orderNo);

        return Result.ok(map);
    }

    //查询订单支付状态
    @GetMapping("/queryPayStatus/{orderNo}")
    public Result queryPayStatus(@PathVariable("orderNo") String orderNo){

        //1 调用微信支付系统接口查询订单支付状态
        Map<String,String> reslutMap =
                weinxinService.queryPayStatus(orderNo);

        //2 微信支付系统返回null 支付失败
        if (reslutMap == null){
            return Result.build(null, ResultCodeEnum.PAYMENT_FAIL);
        }

        //3 通过返回值判断是否成功 微信官方约定的值
        if ("SUCCESS".equals(reslutMap.get("trade_state"))){
            //订单表示
            String out_trade_no = reslutMap.get("out_trade_no");
            //支付成功 修改支付记录表状态 已经支付
            //支付成功 修改订单记录已经支付 库存扣减
            paymentInfoService.paySuccess(out_trade_no,reslutMap);
            return Result.ok(null);
        }

        //4 支付中 等待 定时器 轮询
        return Result.build(null,ResultCodeEnum.PAYMENT_WAITING);

    }


}
